(function($){
  $.extend({
    QEOpt:{
      font:false,
      fontSize:false,
      style:false,
      list:false,
      align:false,
      link:false,
      media:false,
      emoji:false,
      rdud:false
    },
    quickEditOption:function(obj){
      obj=obj||{};
      for (const key in $.QEOpt) {
      if (obj.hasOwnProperty(key)) {
          $.QEOpt[key]=obj[key];          
        }
      }
      return $.QEOpt;
    },
    bootModal: function(title, body, size) {
      var _this = this;
      var temp = $(`
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog ${!!size?'modal-'+size:''}" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" role="remove" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">${title}</h4>
            </div>
            <div class="modal-body">
              ${body}
            </div>
            <div class="modal-footer">
              <button type="button" role="remove" data-dismiss="modal" class="btn btn-default">取消</button>
              <button type="button" role="submit" class="btn btn-primary">保存</button>
            </div>
          </div>
        </div>
      </div>
      `)
      temp.appendTo('body');
      temp.on('click', '[role=submit]', function() {
        temp.trigger('submitClick', temp)
      })
      temp.on('hidden.bs.modal', function() {
        temp.remove();
      })
      temp.show = function() {
        temp.modal('show')
        return temp;
      }
      temp.hide = function() {
        temp.modal('hide')
        return temp;
      }
      temp.toggle = function() {
        temp.modal('toggle')
        return temp;
      }
      if(temp.find('form').length>0){
        var form=temp.find('form')
        function preventEnter (event){
          if(event.keyCode==13){event.preventDefault()}
        }
        form.find('input').on('keydown',function(e){preventEnter(e)})
        form.find('textarea').on('keydown',function(e){preventEnter(e)})
        form.find('[name]').on('keydown',function(e){preventEnter(e)})
      }
      return temp;
    },
  })
  $.fn.extend({
    quickEdit:function(optObj){
      var optObj=optObj||{};
      var option=JSON.parse(JSON.stringify($.quickEditOption()));
      var 
      option=$.extend(option,optObj);
      this.each(function(){
        // console.log(option)
        var baseID=Date.now();
        var toolStr=``;
        var toolbar={
          font:`
          <div class="btn-group">
            <a class="btn dropdown-toggle" data-toggle="dropdown"  data-placement="bottom" title="Font"><i class="icon-font"></i><b class="caret"></b></a>
            <ul class="dropdown-menu"></ul>
          </div>
          `,
          fontSize:`
          <div class="btn-group">
            <a class="btn dropdown-toggle" data-toggle="dropdown"  data-placement="bottom" title="Font Size"><i class="icon-text-height"></i>&nbsp;<b class="caret"></b></a>
            <ul class="dropdown-menu">
              <li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>
              <li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>
              <li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>
            </ul>
          </div>
          `,
          style:`
          <div class="btn-group">
            <a class="btn" data-edit="bold"  data-placement="bottom" title="Bold|加粗 (Ctrl/Cmd+B)"><i class="icon-bold"></i></a>
            <a class="btn" data-edit="italic"  data-placement="bottom" title="Italic|斜体 (Ctrl/Cmd+I)"><i class="icon-italic"></i></a>
            <a class="btn" data-edit="strikethrough"  data-placement="bottom" title="Strikethrough|删除线"><i class="icon-strikethrough"></i></a>
            <a class="btn" data-edit="underline"  data-placement="bottom" title="Underline|下划线 (Ctrl/Cmd+U)"><i class="icon-underline"></i></a>
          </div>
          `,
          list:`
          <div class="btn-group">
            <a class="btn" data-edit="insertunorderedlist"  data-placement="bottom" title="Bullet list|无序列表"><i class="icon-list-ul"></i></a>
            <a class="btn" data-edit="insertorderedlist"  data-placement="bottom" title="Number list|有序列表"><i class="icon-list-ol"></i></a>
            <a class="btn" data-edit="outdent"  data-placement="bottom" title="Reduce indent|撤销缩进 (Shift+Tab)"><i class="icon-indent-left"></i></a>
            <a class="btn" data-edit="indent"  data-placement="bottom" title="Indent|缩进 (Tab)"><i class="icon-indent-right"></i></a>
          </div>
          `,
          align:`
          <div class="btn-group">
            <a class="btn" data-edit="justifyleft"  data-placement="bottom" title="Align Left|左对齐 (Ctrl/Cmd+L)"><i class="icon-align-left"></i></a>
            <a class="btn" data-edit="justifycenter"  data-placement="bottom" title="Center|居中 (Ctrl/Cmd+E)"><i class="icon-align-center"></i></a>
            <a class="btn" data-edit="justifyright"  data-placement="bottom" title="Align Right|右对齐 (Ctrl/Cmd+R)"><i class="icon-align-right"></i></a>
            <a class="btn" data-edit="justifyfull"  data-placement="bottom" title="Justify|两端对齐 (Ctrl/Cmd+J)"><i class="icon-align-justify"></i></a>
          </div>
          `,
          link:`
          <div class="btn-group">
            <a class="btn dropdown-toggle" data-toggle="dropdown"  data-placement="bottom" title="Hyperlink|超链接"><i class="icon-link"></i></a>
              <div class="dropdown-menu input-append">
                <input class="span2" placeholder="URL" type="text" data-edit="createLink"/>
                <button class="btn" type="button">+</button>
              </div>
            <a class="btn" data-edit="unlink"  data-placement="bottom" title="Remove Hyperlink|删除超链接"><i class="icon-cut"></i></a>
          </div>
          `,
          media:`
          <div class="btn-group">
            <label for="file${baseID}">
              <a class="btn"  data-placement="bottom" title="插入图片" id="pictureBtn${baseID}">
              <i class="icon-picture"></i>
              </a>
            </label>
            <input type="file" data-role="magic-overlay" data-target="#pictureBtn${baseID}" id="file${baseID}" data-edit="insertImage" />
          </div>
          `,
          emoji:`
          <div class="btn-group">
            <a class="btn"  data-placement="bottom" title="emoji|表情" id="emojiBtn${baseID}">:)</a>
          </div>
          `,
          rdud:`
          <div class="btn-group">
            <a class="btn" data-edit="undo"  data-placement="bottom" title="Undo|撤销 (Ctrl/Cmd+Z)"><i class="icon-undo"></i></a>
            <a class="btn" data-edit="redo"  data-placement="bottom" title="Redo|重做 (Ctrl/Cmd+Y)"><i class="icon-repeat"></i></a>
          </div>
          `
        }
        for (const key in toolbar) {
          if(option[key]){
            toolStr+=toolbar[key]
          }
        }
        $(this).html(`
        <div id="${baseID}" class="btn-toolbar" data-role="editor-toolbar" data-target="#editor${baseID}">
          ${toolStr}
          <input type="text" data-edit="inserttext" id="voiceBtn${baseID}" class="voiceBtn" x-webkit-speech="">
        </div>
        <div id="editor${baseID}" class="editor"></div>
        `)
        function initToolbarBootstrapBindings() {
          //字体列表
          var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier','Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times','Times New Roman', 'Verdana'],
          fontTarget = $('[title=Font]').siblings('.dropdown-menu');
          $.each(fonts, function (idx, fontName) {
            fontTarget.append($('<li><a data-edit="fontName ' + fontName +'" style="font-family:\''+ fontName +'\'">'+fontName + '</a></li>'));
          });
          //初始化工具提示
          $('[title]').tooltip({container:'body'});
          
          $('.dropdown-menu input').click(function() {return false;})
            .change(function () {$(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');})
            .keydown('esc', function () {this.value='';$(this).change();});
          $('[data-role=magic-overlay]').each(function () { 
            var overlay = $(this), target = $(overlay.data('target')); 
            overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
          });
          if ("onwebkitspeechchange" in document.createElement("input")) {
            var editorOffset = $(`#editor${baseID}`).offset();
            $(`#voiceBtn${baseID}`).css('position','absolute').offset({top: editorOffset.top, left: editorOffset.left+$(`#editor${baseID}`).innerWidth()-35});
          } else {
            $(`#voiceBtn${baseID}`).hide();
          }
        };//initToolbarBootstrapBindings END
        function showErrorAlert (reason, detail) {
          var msg='';
          if (reason==='unsupported-file-type') { msg = "Unsupported format " +detail; }
          else {
            console.log("error uploading file", reason, detail);
          }
          $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>'+ 
          '<strong>File upload error</strong> '+msg+' </div>').prependTo(this);
        };//showErrorAlert END
        initToolbarBootstrapBindings();
        $(`#editor${baseID}`).wysiwyg({fileUploadError: showErrorAlert});
          window.prettyPrint && prettyPrint();
          if(option.emoji){
            $(`#editor${baseID}`).emoji(
              {
                button:`#${baseID} #emojiBtn${baseID}`,
                showTab: true,
                animation: 'none',            
                icons: [
                  {
                    name: "贴吧表情",
                    path: "/emoji/tieba/",
                    maxNum: 50,
                    file: ".jpg",
                    placeholder: ":{alias}:",
                    alias: {
                        1: "hehe",
                        2: "haha",
                        3: "tushe",
                        4: "a",
                        5: "ku",
                        6: "lu",
                        7: "kaixin",
                        8: "han",
                        9: "lei",
                        10: "heixian",
                        11: "bishi",
                        12: "bugaoxing",
                        13: "zhenbang",
                        14: "qian",
                        15: "yiwen",
                        16: "yinxian",
                        17: "tu",
                        18: "yi",
                        19: "weiqu",
                        20: "huaxin",
                        21: "hu",
                        22: "xiaonian",
                        23: "neng",
                        24: "taikaixin",
                        25: "huaji",
                        26: "mianqiang",
                        27: "kuanghan",
                        28: "guai",
                        29: "shuijiao",
                        30: "jinku",
                        31: "shengqi",
                        32: "jinya",
                        33: "pen",
                        34: "aixin",
                        35: "xinsui",
                        36: "meigui",
                        37: "liwu",
                        38: "caihong",
                        39: "xxyl",
                        40: "taiyang",
                        41: "qianbi",
                        42: "dnegpao",
                        43: "chabei",
                        44: "dangao",
                        45: "yinyue",
                        46: "haha2",
                        47: "shenli",
                        48: "damuzhi",
                        49: "ruo",
                        50: "OK"
                    },
                    title: {
                        1: "呵呵",
                        2: "哈哈",
                        3: "吐舌",
                        4: "啊",
                        5: "酷",
                        6: "怒",
                        7: "开心",
                        8: "汗",
                        9: "泪",
                        10: "黑线",
                        11: "鄙视",
                        12: "不高兴",
                        13: "真棒",
                        14: "钱",
                        15: "疑问",
                        16: "阴脸",
                        17: "吐",
                        18: "咦",
                        19: "委屈",
                        20: "花心",
                        21: "呼~",
                        22: "笑脸",
                        23: "冷",
                        24: "太开心",
                        25: "滑稽",
                        26: "勉强",
                        27: "狂汗",
                        28: "乖",
                        29: "睡觉",
                        30: "惊哭",
                        31: "生气",
                        32: "惊讶",
                        33: "喷",
                        34: "爱心",
                        35: "心碎",
                        36: "玫瑰",
                        37: "礼物",
                        38: "彩虹",
                        39: "星星月亮",
                        40: "太阳",
                        41: "钱币",
                        42: "灯泡",
                        43: "茶杯",
                        44: "蛋糕",
                        45: "音乐",
                        46: "haha",
                        47: "胜利",
                        48: "大拇指",
                        49: "弱",
                        50: "OK"
                    }
                  }, 
                  {
                    path: "/emoji/qq/",
                    name:'QQ表情',
                    maxNum: 91,
                    excludeNums: [41, 45, 54],
                    file: ".gif",
                    placeholder: "#qq_{alias}#"
                  }
                ]
              });
          }
         
      })//each END
    },//quickEdit END
    serializeObject: function() {
      //当匹配到的表单数量大于1时弹出警告
      if (this.length > 1) console.warn('CH:选择器同时选中了多个表单，这可能不是你需要的状态');
      if (this.length > 1) console.warn('EN:multiply forms selected');
      var obj = {};
      $.each(this.serializeArray(), function(index) {
        //对存在多个name相同的表单元素进行处理
        if (!!obj[this['name']]) {
          if (!!!$.isArray(obj[this['name']])) {
            obj[this['name']] = [obj[this['name']]]
          }
          obj[this['name']].push(this['value'])
        } else {
          obj[this['name']] = this['value'];
        }
      });
      for (const key in obj) {
        if (obj[key]=="undefined") {
          // delete obj[key]
          obj[key]=null
        }
      }
      return obj;
    },//serializeObject END
  })
})(jQuery)